package com.youtui.common.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import sun.misc.BASE64Decoder;

/**
 * @author chailj
 * @date 2016年5月31日
 */

@SuppressWarnings("restriction")
@Component
public class FileUploadUtil {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

	
	// base64编码生成文件
	public String GenerateImage(String localPath, String imgStr, String fileName) {
		File localPathFile = new File(localPath + "upload" + File.separator);
		if (!localPathFile.exists()) {
			localPathFile.mkdir();
		}

		Long timestamp = DateUtils.getTimestamp();

		String pathURI = "upload/" + timestamp + fileName;
		String path = localPath + "upload"+File.separator+ timestamp + fileName;
		logger.debug(path);
		// 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try { // Base64解码
			byte[] bytes = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {
					// 调整异常数据
					bytes[i] += 256;
				}
			} // 生成jpeg图片

			DataOutputStream out = new DataOutputStream(new FileOutputStream(path));// 存放文件的绝对路径
			out.write(bytes);
			out.flush();
			out.close();
			return pathURI;
		} catch (Exception e) {
			return "";
		}
	}

}
